<?php
/*
	Copyright (C) 2008 - 2012 Inanta Martsanto
	Inanta Martsanto (inanta@inationsoft.com)

	This file is part of NewStep Framework.

	NewStep Framework is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	NewStep Framework is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with NewStep Framework.  If not, see <http://www.gnu.org/licenses/>.
*/

namespace Inationsoft\NS\Database\Driver;

use Inationsoft\NS\Database\Database;
use Inationsoft\NS\Database\IDatabaseDriver;
use Inationsoft\NS\Exception\LibraryException;
use Inationsoft\NS\Exception\DatabaseException;

/**
 *Driver for opening and handle SQLite file
 *
 *@author Inanta Martsanto <inanta@inationsoft.com>
 */
class SQLite2Driver extends DatabaseDriver implements IDatabaseDriver {
	function __construct($args = array()) {
		if(!function_exists('sqlite_open')) throw new LibraryException(array('code' => NS_EX_LIB_NOT_INSTALLED, 'class' => __CLASS__, 'library' => 'SQLite'));
		
		$this->createProperties(array(
			'Database' => isset($args['database']) ? $args['database'] : KOMA_DB_NAME,
			'Persistent' => isset($args['persistent']) ? $args['persistent'] : KOMA_DB_PCONNECTION,
			'Mode' => isset($args['mode']) ? $args['mode'] : 0666));

		parent::__construct();
	}

	function __destruct() { $this->close(); }

	function affectedRows() {
		return @sqlite_changes($this->Connection);
	}

	function close() {
		@sqlite_close($this->Connection);
	}

	function connect() {
		$this->Connection = ($this->Persistent ? @sqlite_popen($this->Database, $this->Mode) : @sqlite_open($this->Database, $this->Mode));

		if(!is_resource($this->Connection)) {
			throw new DatabaseException(array('code' => UNABLE_TO_USE, 'database' => $this->Database));
		}
	}

	function fetchArray($result = null) {
		$this->assignResult($result);
		return @sqlite_fetch_array($this->Result);
	}

	function fetchAssoc($result = null) {
		return $this->fetchArray($result);
	}
	
	function fetchRow($result = null) {
		return $this->fetchArray($result);
	}
	
	function numRows($result = null) {
		$this->assignResult($result);
		return @sqlite_num_rows($this->Result);
	}

	function lastInsertID() { throw new UnsupportedOperationException(__METHOD__); }

	function query($query) {
		$this->Result = @sqlite_query($query, $this->Connection);
		if($this->Result) return $this->Result;
		
		return false;
	}

	static function getInstance($args = array()) { return self::createInstance(__CLASS__, $args); }
}
?>
